<template>
  <basic-modal
    v-bind="$attrs"
    show-cancel
    show-confirm
    :confirm-loading="confirmLoading"
    @confirm="hanleSubmit"
  >
    <n-form ref="formRef" :model="modelForm" :rules="rules">
      <n-grid :cols="24" :x-gap="10" :y-gap="10">
        <n-gi :span="12">
          <n-form-item label="店铺名称" path="name">
            <n-input
              placeholder="请输入客户名称"
              v-model:value="modelForm.name"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="店铺类型" path="branchType">
            <n-select
              :options="BRANCH_TYPE_LIST"
              placeholder="请选择店铺类型"
              v-model:value="modelForm.branchType"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="店铺所在省份" path="province">
            <n-input
              placeholder="请输入店铺所在省份"
              v-model:value="modelForm.province"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="店铺所在市" path="city">
            <n-input
              placeholder="请输入店铺所在市"
              v-model:value="modelForm.city"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="店铺所在区" path="district">
            <n-input
              placeholder="请输入店铺所在区"
              v-model:value="modelForm.district"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="邮编" path="postCode">
            <n-input
              placeholder="请输入邮编"
              v-model:value="modelForm.postCode"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="24">
          <n-form-item label="详细地址" path="address">
            <n-input
              placeholder="请输入店铺详细地址"
              v-model:value="modelForm.address"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="24">
          <n-form-item label="联系方式" path="contactNumber">
            <n-input
              placeholder="请输入店铺联系方式"
              v-model:value="modelForm.contactNumber"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="店铺管理员" path="managerId">
            <n-select
              placeholder="请选择店铺管理员"
              v-model:value="modelForm.managerId"
              :loading="userSearchLoading"
              remote
              clearable
              filterable
              multiple
              :options="userList"
              value-field="id"
              label-field="realname"
              @search="handleSearchUser"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="交易缺省客户" path="walkinCustomerId">
            <n-select
              placeholder="请选择交易缺省客户"
              v-model:value="modelForm.walkinCustomerId"
              :loading="customerSearchLoading"
              remote
              clearable
              filterable
              :options="customersList"
              value-field="id"
              label-field="name"
              @search="handleSearchCustomer"
            />
          </n-form-item>
        </n-gi>
      </n-grid>
    </n-form>
  </basic-modal>
</template>
<script lang="ts" setup>
import { reactive, ref, useAttrs } from "vue";
import { FormInst, useMessage } from "naive-ui";
import { debounce, get } from "lodash-es";
import { useSearchCustomers } from "@/components/biz/customerModal/hooks";
import { createBranch } from "@/api/branches/branches.api";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { DictStorage } from "@/storage/dict.storage";
import { getUserList } from "@/api/user/user.api";
import { IBranchModalProps } from "./props";

const BRANCH_TYPE_LIST = DictStorage.getDictItemsByCode("pos_branch_type");

const rules = {
  name: [
    {
      required: true,
      message: "请输入店铺名称",
      trigger: "change",
    },
  ],
  branchType: [
    {
      required: true,
      message: "请输入店铺类型",
      trigger: "change",
    },
  ],
  province: [
    {
      required: true,
      message: "请输入店铺所在省份",
      trigger: "change",
    },
  ],
  city: [
    {
      required: true,
      message: "请输入店铺所在市",
      trigger: "change",
    },
  ],
  district: [
    {
      required: true,
      message: "请输入店铺所在区",
      trigger: "change",
    },
  ],
  address: [
    {
      required: true,
      message: "请输入店铺详细地址",
      trigger: "change",
    },
  ],
  postCode: [
    {
      required: true,
      message: "请输入邮编",
      trigger: "change",
    },
  ],
  contactNumber: [
    {
      required: true,
      message: "请输入联系方式",
      trigger: "change",
    },
  ],
};

const $attrs = useAttrs();
const message = useMessage();

const emits = defineEmits(["confirm"]);

const props = withDefaults(defineProps<IBranchModalProps>(), {
  actionType: ActionTypeEnum.ADD,
});

const { customersList, customerSearchLoading, handleSearchCustomer } =
  useSearchCustomers();

const confirmLoading = ref<boolean>(false);
const formRef = ref<FormInst | null>(null);

const userSearchLoading = ref<boolean>(false);
const userList = ref<any[]>([]);

const modelForm = reactive({
  id: "",
  name: "",
  branchType: undefined,
  walkinCustomerId: undefined,
  latitude: "",
  longitude: "",
  province: "",
  city: "",
  district: "",
  address: "",
  postCode: "",
  contactNumber: "",
  managerId: undefined,
});

const hanleSubmit = async () => {
  formRef.value?.validate(async (errors) => {
    if (errors) {
      message.error("请正确输入表单项");
      return;
    }

    if (props.actionType === ActionTypeEnum.ADD) {
      handleAddBranch();
    }
  });
};

const handleAddBranch = async () => {
  try {
    confirmLoading.value = true;
    const res = await createBranch(modelForm);
    console.log(res);
    emits("confirm");
  } finally {
    confirmLoading.value = false;
  }
};

const handleSearchUser = debounce(async function (keyword: string) {
  if (keyword) {
    try {
      userSearchLoading.value = true;
      const res = await getUserList({
        realname: `${keyword}`,
        page: 1,
        pageSize: 100,
        pageCount: 1,
      });
      // http://localhost:5173/jeecgboot/pos/users/list?page=1&pageSize=10&pageCount=1&realname=001&username=
      // http://localhost:5173/jeecgboot/pos/users/list?realname=*001*&page=1&pageSize=100&pageCount=1
      userList.value = get(res, "result.records") || [];
    } finally {
      userSearchLoading.value = false;
    }
  }
}, 200);
</script>
